//
//  ST_ConversionListViewController.swift
//  btvideo
//
//  Created by mac on 2020/10/10.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyUserDefaults
import SwiftyAttributes

class ST_ConversionListViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("积分兑换")
        
        if Defaults[.isPanda]  == false{
        
            self.right_nav_btn.isHidden = false
            let str = "兑换记录".withAttributes([Attribute.font(Font.systemFont(ofSize: 14)),Attribute.textColor(UIColor.init(hex: 0x3598FF)!)])
            self.right_nav_btn.setAttributedTitle(str, for: UIControl.State.normal)
        }
        
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-12)
            make.bottom.equalTo(own_navigation_bar)
            make.height.equalTo(44)
            make.width.equalTo(80)
        }

        
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        request_data()
        
        NotificationCenter.default.addObserver(self, selector: #selector(bind_header_data), name: Notification.Name.modifyIncomeCoin, object: nil)
        
    }
    
    deinit {
        
        
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func bind_header_data(){
        
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo {
            headerView?.value = user.income
        }else{
            headerView?.value = 0
        }
    }
    
    fileprivate func request_data(){
        
        
        JVrequest(PH.fetchConversionListApi, success: { (json) in
            
            self.data_array = json["data"].arrayValue.map { (itemJson) -> ST_ConversionGoodsModel in
                return ST_ConversionGoodsModel.init(fromJson: itemJson)
            }
            self.collectionView.reloadData {
                
            }
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
    }
    
    
    
//    MARK: - event
    override func right_click() {
        
        self.navigationController?.pushViewController(ST_ConversionHistoryViewController())
    }
    
//    MARK: - Properties
    fileprivate lazy var data_array = [ST_ConversionGoodsModel]()
    
    fileprivate var headerView:ST_ConversionListHeaderView?
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
      let controlLayout = UICollectionViewFlowLayout()
       controlLayout.minimumLineSpacing = 15
       controlLayout.minimumInteritemSpacing = 15
       controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 15)
        let w = (ScreenWidth - 15 * 3)/2.0
        controlLayout.itemSize = CGSize.init(width: w, height: (w - 20)/145.0*100 + 10 + 10 + 20 + 33 )
        controlLayout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 40 + 15)
       return controlLayout
   }()
       
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = UIColor.init(hex: 0xF5F8FA)
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_ConversionListCollectionCell.self)
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_ConversionListHeaderView.self)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 60+BTSafeAreaBottom, right: 0)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
}

extension ST_ConversionListViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ConversionListCollectionCell.self, for: indexPath)
        
        cell.data = data_array[safe:indexPath.row]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_ConversionListHeaderView.self, for: indexPath)
        
        
        self.headerView = header
        
        self.bind_header_data()
        
        return header
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let vc = ST_ConversionDetailViewController()
        
        vc.data = data_array[safe:indexPath.row]
        
        self.navigationController?.pushViewController(vc)
        
    }
    
}


//MARK: - Cell
class ST_ConversionListCollectionCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .white
        contentView.cornerRadius = 10
        
        contentView.addSubview(icon_image_view)
        contentView.addSubview(key_label)
        contentView.addSubview(value_label)
        
        
        icon_image_view.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-33-20-10)
        }
        
        key_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(icon_image_view.snp.bottom).offset(10)
            make.height.equalTo(20)
        }
        
        
        value_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(key_label.snp.bottom).offset(3)
            make.height.equalTo(20)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var icon_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        return control
    }()
    
    
    fileprivate lazy var key_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#3A3A3A")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()

    fileprivate lazy var value_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#FEC207")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    var data:ST_ConversionGoodsModel?{
        didSet{
            
            guard let d = data else { return  }
            
            icon_image_view.pin_setImage(from:d.image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            key_label.text = d.name
            
            value_label.text = d.integral.string + " \(Defaults[.PandaStr])"
            
        }
    }
}

//MARK: - Model

class ST_ConversionGoodsModel : NSObject{

    var id : Int
    var image : String
    var integral : Int
    var money : Int
    var name : String
    /**
     2 是需要判断的 提xian
     */
    var type : Int

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        id = json["id"].intValue
        image = json["image"].stringValue
        integral = json["integral"].intValue
        money = json["money"].intValue
        name = json["name"].stringValue
        type = json["type"].intValue
        
        super.init()
        
    }

}

//MARK: - Header

class ST_ConversionListHeaderView: UICollectionReusableView {
        
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = .clear
        
        
        self.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 0, bottom: 15, right: 0))
        }
        
        root_view.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        return control
    }()
    
    var value = 0.0{
        didSet{
            
            let str = "\(Defaults[.PandaStr])：".withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0x333333)!)])
            
            str.append(String(format: "%.2f \(Defaults[.PandaStr])", value).withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!)]))
            
            content_label.attributedText = str
            
        }
    }
    
}
